﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using SapB1WebPOS.BLL;
using System.Data;
using Newtonsoft.Json;
using System.Web.Script.Services;
using SapB1WebPOS.Utils;
using SapB1WebPOS.DAL;
using System.Printing;
namespace SapB1WebPOS
{
    public partial class SapPOS : System.Web.UI.Page
    {
        public class Response
        {
            public List<Model.INV1> Data { get; set; }
            public int Count { get; set; }
            public string Errors { get; set; }

            public Response(List<Model.INV1> data, int count)
            {
                this.Data = data;
                this.Count = count;
            }

            public Response(string errors)
            {
                this.Errors = errors;
            }

            public Response()
            {

            }
        }
        public class Payment
        {
            public string PaymentType { get; set; }
            public string PaymentCode { get; set; }
            public string PaymentName { get; set; }
            public double Amount { get; set; }
            public string AcctCode { get; set; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {

        }
        [WebMethod]
        public static string GetSAPItemPrice(string cardCode, string itemCode, float amount, DateTime refDate)
        {
            try
            {
                string sapUser = string.Empty;
                string sapPassword = string.Empty;
                string companyDB = string.Empty;
                if (HttpContext.Current.Session["LoginUserName"] != null)
                {
                    sapUser = HttpContext.Current.Session["LoginUserName"].ToString();
                }
                if (HttpContext.Current.Session["LoginPassword"] != null)
                {
                    sapPassword = HttpContext.Current.Session["LoginPassword"].ToString();
                }
                if (HttpContext.Current.Session["CompanyDB"] != null)
                {
                    companyDB = HttpContext.Current.Session["CompanyDB"].ToString();
                }
                if (sapUser.Length > 0 && sapPassword.Length > 0 && companyDB.Length > 0)
                {
                    SAPTransaction obj = new SAPTransaction();
                    return obj.GetSAPItemPrice(sapUser, sapPassword, companyDB, cardCode, itemCode, amount, refDate).ToString();
                }
            }
            catch (Exception ex)
            {
                Log.WriteException(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "SystemError", ex);
                return "0";
            }
            return "0";
        }
        [WebMethod]
        public static string GetWareHouses()
        {
            try
            {
                string companyDB = string.Empty;

                if (HttpContext.Current.Session["CompanyDB"] != null)
                {
                    companyDB = HttpContext.Current.Session["CompanyDB"].ToString();
                }
                if (companyDB.Length > 0)
                {
                    CommonBLL obj = new CommonBLL();
                    DataSet dsData = obj.GetWareshouse(companyDB);
                    if (dsData != null)
                    {
                        return JsonConvert.SerializeObject(dsData.Tables[0]);
                    }
                }
            }
            catch (Exception ex)
            {
                Log.WriteException(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "SystemError", ex);
            }
            return string.Empty;
        }
        [WebMethod]
        public static string GetTaxs()
        {
            try
            {
                string companyDB = string.Empty;

                if (HttpContext.Current.Session["CompanyDB"] != null)
                {
                    companyDB = HttpContext.Current.Session["CompanyDB"].ToString();
                }
                if (companyDB.Length > 0)
                {
                    CommonBLL obj = new CommonBLL();
                    DataSet dsData = obj.GetTax(companyDB, "O");
                    if (dsData != null)
                    {
                        return JsonConvert.SerializeObject(dsData.Tables[0]);
                    }
                }
            }
            catch (Exception ex)
            {
                Log.WriteException(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "SystemError", ex);
            }
            return string.Empty;
        }
        [WebMethod]
        public static string GetBPByCardCode(string cardCode)
        {
            try
            {
                string companyDB = string.Empty;

                if (HttpContext.Current.Session["CompanyDB"] != null)
                {
                    companyDB = HttpContext.Current.Session["CompanyDB"].ToString();
                }
                if (companyDB.Length > 0)
                {
                    BusinessPartnersBLL obj = new BusinessPartnersBLL();
                    DataSet dsData = obj.GetOCRDByCardCode(companyDB, cardCode, "C");
                    if (dsData != null)
                    {
                        return JsonConvert.SerializeObject(dsData.Tables[0]);
                    }
                }
            }
            catch (Exception ex)
            {
                Log.WriteException(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "SystemError", ex);
            }
            return string.Empty;
        }
        [WebMethod]
        public static string GetDefaultBP()
        {
            try
            {
                string companyDB = string.Empty;

                if (HttpContext.Current.Session["CompanyDB"] != null)
                {
                    companyDB = HttpContext.Current.Session["CompanyDB"].ToString();
                }
                if (companyDB.Length > 0)
                {
                    BusinessPartnersBLL obj = new BusinessPartnersBLL();
                    DataSet dsData = obj.GetDefaultOCRD(companyDB);
                    if (dsData != null)
                    {
                        return JsonConvert.SerializeObject(dsData.Tables[0]);
                    }
                }
            }
            catch (Exception ex)
            {
                Log.WriteException(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "SystemError", ex);
            }
            return string.Empty;
        }
        [WebMethod]
        [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
        public static void ClearSessionData()
        {
            HttpContext.Current.Session["DocList"] = null;
            HttpContext.Current.Session["DocCount"] = null;
            HttpContext.Current.Session["DeleteDocList"] = null;
            HttpContext.Current.Session["DataType"] = null;
            HttpContext.Current.Session["PaymentList"] = null;
            HttpContext.Current.Session["PrintHeaderData"] = null;
            HttpContext.Current.Session["PrintLineData"] = null;
        }
        [WebMethod]
        [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
        public static string CancelDoc(string docEntry)
        {
            try
            {
                SAPTransaction obj = new SAPTransaction();
                DataTable tbResult = new DataTable();
                string sapUser = string.Empty;
                string sapPassword = string.Empty;
                string companyDB = string.Empty;
                if (HttpContext.Current.Session["LoginUserName"] != null)
                {
                    sapUser = HttpContext.Current.Session["LoginUserName"].ToString();
                }
                if (HttpContext.Current.Session["LoginPassword"] != null)
                {
                    sapPassword = HttpContext.Current.Session["LoginPassword"].ToString();
                }
                if (HttpContext.Current.Session["LoginPassword"] != null)
                {
                    companyDB = HttpContext.Current.Session["CompanyDB"].ToString();
                }
                if (sapUser.Length > 0 && sapPassword.Length > 0 && companyDB.Length > 0)
                {
                    string docType = ConvertDocType.Get2String(DocType.AR_INVOICE);
                    tbResult = obj.CloseCancelDocument(sapUser, sapPassword, companyDB, docType, docEntry, true);
                    if (tbResult != null && tbResult.Rows.Count > 0)
                    {
                        if ((int)tbResult.Rows[0]["ErrCode"] != 0)
                        {
                            return "Error: " + tbResult.Rows[0]["ErrMsg"].ToString();
                        }
                        else
                        {
                            return tbResult.Rows[0]["ErrMsg"].ToString();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.WriteException(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "SystemError", ex);
            }
            return docEntry;
        }
        [WebMethod]
        [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
        public static string UpdateDocToDB(string oDocHeader, bool isUpdate, string docEntry, string paymentData)
        {
            try
            {
                Model.OINV header = JsonConvert.DeserializeObject<Model.OINV>(oDocHeader);
                List<Payment> lstPayment = JsonConvert.DeserializeObject<List<Payment>>(paymentData);
                List<Model.INV1> lstDocLine = new List<Model.INV1>();

                if (HttpContext.Current.Session["DocList"] != null)
                {
                    lstDocLine = (List<Model.INV1>)HttpContext.Current.Session["DocList"];
                }

                if (header != null)
                {
                    string loginUser = string.Empty;
                    string loginPass = string.Empty;
                    string companyDB = string.Empty;

                    if (HttpContext.Current.Session["LoginUserName"] != null)
                    {
                        loginUser = HttpContext.Current.Session["LoginUserName"].ToString();
                    }
                    if (HttpContext.Current.Session["LoginPassword"] != null)
                    {
                        loginPass = HttpContext.Current.Session["LoginPassword"].ToString();
                    }
                    if (HttpContext.Current.Session["CompanyDB"] != null)
                    {
                        companyDB = HttpContext.Current.Session["CompanyDB"].ToString();
                    }

                    string objType = ConvertDocType.Get2String(DocType.AR_INVOICE);

                    DataTable tbHeader = new DataTable(TableNameDefined.AR_INVOICE_HEADER);
                    tbHeader.Columns.Add("DocEntry");
                    tbHeader.Columns.Add("CardCode");
                    tbHeader.Columns.Add("CardName");
                    tbHeader.Columns.Add("DocDate");
                    tbHeader.Columns.Add("DocDueDate");
                    tbHeader.Columns.Add("TaxDate");
                    tbHeader.Columns.Add("Comments");
                    tbHeader.Columns.Add("ObjType");
                    tbHeader.Columns.Add("DocTotal");
                    if (!(bool)HttpContext.Current.Session["IsSAPUser"])
                    {
                        tbHeader.Columns.Add("U_WebUser");
                    }

                    DataRow rHeader = tbHeader.NewRow();
                    rHeader["DocEntry"] = header.DocEntry;
                    rHeader["CardCode"] = header.CardCode;
                    rHeader["CardName"] = header.CardName;
                    rHeader["DocDate"] = header.DocDate;
                    rHeader["DocDueDate"] = header.DocDueDate;
                    rHeader["TaxDate"] = header.TaxDate;
                    rHeader["Comments"] = header.Comments;
                    rHeader["ObjType"] = objType;
                    rHeader["DocTotal"] = header.DocTotal;
                    if (!(bool)HttpContext.Current.Session["IsSAPUser"])
                    {
                        rHeader["U_WebUser"] = loginUser;
                    }

                    tbHeader.Rows.Add(rHeader);

                    DataTable tbLine = Utils.Utils.ToDataTable<Model.INV1>(lstDocLine);
                    DataTable tbPayment = Utils.Utils.ToDataTable<Payment>(lstPayment);

                    tbLine.Columns.Remove("OnHand");
                    tbLine.Columns.Remove("TotalBefDisc");
                    tbLine.Columns.Remove("Total");
                    tbLine.Columns.Remove("LineStatus");
                    tbLine.Columns.Remove("VatGroupName");
                    tbLine.Columns.Remove("WhsName");

                    DataSet dsUpdate = new DataSet();
                    dsUpdate.Tables.Add(tbHeader);
                    dsUpdate.Tables.Add(tbLine);
                    dsUpdate.Tables.Add(tbPayment);

                   
                    if (loginUser.Length > 0 && loginPass.Length > 0 && companyDB.Length > 0)
                    {
                        if (dsUpdate.Tables.Count > 2)
                        {
                            SAPTransaction obj = new SAPTransaction();
                            string errMsg = obj.Pos2SAP(loginUser, loginPass, companyDB, dsUpdate);
                            return errMsg;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.WriteException(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "SystemError", ex);
                return ex.Message;
            }
            return "0";
        }
        [WebMethod]
        [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
        public static void DeleteDocLine(string lineNum)
        {
            try
            {
                if (HttpContext.Current.Session["DocList"] != null)
                {
                    List<Model.INV1> lstDocLine = (List<Model.INV1>)HttpContext.Current.Session["DocList"];
                    Model.INV1 updateLine = lstDocLine.FirstOrDefault(u => u.LineNum == lineNum);
                    if (updateLine.DocEntry != null && updateLine.DocEntry.Length > 0)
                    {
                        List<Model.INV1> lstDeleteDocLine;
                        if (HttpContext.Current.Session["DeleteDocList"] != null)
                        {
                            lstDeleteDocLine = (List<Model.INV1>)HttpContext.Current.Session["DeleteDocList"];
                        }
                        else
                        {
                            lstDeleteDocLine = new List<Model.INV1>();
                        }
                        lstDeleteDocLine.Add(updateLine);
                        HttpContext.Current.Session["DeleteDocList"] = lstDeleteDocLine;
                        lstDocLine.Remove(updateLine);
                    }
                    else
                    {
                        lstDocLine.Remove(updateLine);
                    }
                    HttpContext.Current.Session["DocList"] = lstDocLine;
                    HttpContext.Current.Session["DocCount"] = lstDocLine.Count;
                }
            }
            catch (Exception ex)
            {
                Log.WriteException(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "SystemError", ex);
            }
        }

        [WebMethod]
        [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
        public static void UpdateDoc(string oDocLine, string isInsert, string rowIndex)
        {
            try
            {
                Model.INV1 line = JsonConvert.DeserializeObject<Model.INV1>(oDocLine);
                if (HttpContext.Current.Session["DocList"] != null)
                {
                    List<Model.INV1> lstDocLine = (List<Model.INV1>)HttpContext.Current.Session["DocList"];
                    var result = (from m in lstDocLine
                                  select m).OrderByDescending(a => a.LineNum).FirstOrDefault();
                    if (isInsert == "1")
                    {
                        if (result != null)
                        {
                            line.LineNum = (int.Parse(result.LineNum) + 1).ToString();
                        }
                        else
                        {
                            line.LineNum = "0";
                        }
                        lstDocLine.Add(line);
                    }
                    else if (isInsert == "2")
                    {
                        Model.INV1 updateLine = lstDocLine.FirstOrDefault(u => u.LineNum == line.LineNum);
                        int index = lstDocLine.FindIndex(u => u.LineNum == line.LineNum);
                        updateLine.ItemCode = line.ItemCode;
                        updateLine.Dscription = line.Dscription;
                        updateLine.Quantity = line.Quantity;
                        updateLine.WhsCode = line.WhsCode;
                        updateLine.WhsName = line.WhsName;
                        updateLine.VatGroup = line.VatGroup;
                        updateLine.VatGroupName = line.VatGroupName;
                        updateLine.LineTotal = line.LineTotal;
                        updateLine.DiscPrcnt = line.DiscPrcnt;
                        updateLine.PriceBefDi = line.PriceBefDi;
                        updateLine.TotalBefDisc = line.TotalBefDisc;
                        updateLine.Price = line.Price;
                        updateLine.unitMsr = line.unitMsr;
                        updateLine.DocEntry = line.DocEntry;
                        updateLine.LineNum = line.LineNum;
                        updateLine.VatSum = line.VatSum;
                        updateLine.Total = line.Total;
                        updateLine.SlpCode = line.SlpCode;
                    }
                    HttpContext.Current.Session["DocList"] = lstDocLine;
                    HttpContext.Current.Session["DocCount"] = lstDocLine.Count;
                }
            }
            catch (Exception ex)
            {
                Log.WriteException(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "SystemError", ex);
            }
        }
        [WebMethod]
        [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
        public static Response GetDocLines(string docEntry)
        {
            try
            {
                string companyDB = string.Empty;

                if (HttpContext.Current.Session["CompanyDB"] != null)
                {
                    companyDB = HttpContext.Current.Session["CompanyDB"].ToString();
                }
                if (companyDB.Length > 0)
                {
                    if (HttpContext.Current.Session["DocList"] != null)
                    {
                        List<Model.INV1> lstDocLineUpdate = (List<Model.INV1>)HttpContext.Current.Session["DocList"];
                        List<Model.INV1> filteredResults = lstDocLineUpdate.FindAll(p => p.LineStatus != "3");
                        HttpContext.Current.Session["DocList"] = filteredResults;
                        HttpContext.Current.Session["DocCount"] = filteredResults.Count;
                        return new Response(filteredResults, filteredResults.Count);
                    }
                    List<Model.INV1> lstDocLine = new List<Model.INV1>();
                    ARInvoiceBLL obj = new ARInvoiceBLL();
                    DataSet dsData = new DataSet();

                    dsData = obj.GetDocumentLineByDocEntry(companyDB, docEntry);
                    if (dsData != null)
                    {
                        HttpContext.Current.Session["PrintLineData"] = dsData.Tables[0].Copy();
                        foreach (DataRow r in dsData.Tables[0].Rows)
                        {
                            Model.INV1 docLine = new Model.INV1();
                            docLine.DocEntry = r["DocEntry"].ToString();
                            docLine.DiscPrcnt = double.Parse(r["DiscPrcnt"].ToString());
                            docLine.Dscription = r["Dscription"].ToString();
                            docLine.ItemCode = r["ItemCode"].ToString();
                            docLine.LineNum = r["LineNum"].ToString();
                            docLine.LineStatus = r["LineStatus"].ToString();
                            docLine.LineTotal = double.Parse(r["LineTotal"].ToString());
                            docLine.Price = double.Parse(r["Price"].ToString());
                            docLine.PriceBefDi = double.Parse(r["PriceBefDi"].ToString());
                            docLine.Quantity = double.Parse(r["Quantity"].ToString());
                            docLine.unitMsr = r["unitMsr"].ToString();
                            docLine.VatGroup = r["VatGroup"].ToString();
                            docLine.VatGroupName = r["VatGroupName"].ToString();
                            docLine.VatPrcnt = double.Parse(r["VatPrcnt"].ToString());
                            docLine.VatSum = double.Parse(r["VatSum"].ToString());
                            docLine.WhsCode = r["WhsCode"].ToString();
                            docLine.WhsName = r["WhsName"].ToString();
                            docLine.SlpCode = r["SlpCode"].ToString();


                            double totalBeforeDiscount = docLine.Quantity * double.Parse(r["PriceBefDi"].ToString());
                            docLine.TotalBefDisc = totalBeforeDiscount;

                            double total = double.Parse(r["LineTotal"].ToString()) + double.Parse(r["VatSum"].ToString());
                            docLine.Total = total;

                            lstDocLine.Add(docLine);
                        }
                        HttpContext.Current.Session["DocList"] = lstDocLine;
                        HttpContext.Current.Session["DocCount"] = dsData.Tables[0].Rows.Count;
                        var jsonData = new { total = dsData.Tables[0].Rows.Count, lstCustomerProperty = lstDocLine };
                        return new Response(lstDocLine, dsData.Tables[0].Rows.Count);
                    }
                }
            }
            catch (Exception ex)
            {
                Log.WriteException(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "SystemError", ex);
            }
            return new Response();
        }
        [WebMethod]
        public static string GetDocHeaderByDocEntry(string docEntry)
        {
            try
            {
                string companyDB = string.Empty;

                if (HttpContext.Current.Session["CompanyDB"] != null)
                {
                    companyDB = HttpContext.Current.Session["CompanyDB"].ToString();
                }
                if (companyDB.Length > 0)
                {
                    if (docEntry != null && docEntry.Length > 0)
                    {
                        ARInvoiceBLL obj = new ARInvoiceBLL();
                        DataSet dsData = obj.GetDocumentByDocEntry(companyDB, docEntry);
                        if (dsData != null)
                        {
                            HttpContext.Current.Session["PrintHeaderData"] = dsData.Tables[0].Copy();
                            return JsonConvert.SerializeObject(dsData);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.WriteException(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "SystemError", ex);
            }
            return string.Empty;
        }
        [WebMethod]
        public static string GetLastRecord()
        {
            try
            {
                string companyDB = string.Empty;

                if (HttpContext.Current.Session["CompanyDB"] != null)
                {
                    companyDB = HttpContext.Current.Session["CompanyDB"].ToString();
                }
                if (companyDB.Length > 0)
                {
                    ARInvoiceBLL obj = new ARInvoiceBLL();
                    DataSet dsData = obj.GetDocumentLastRecord(companyDB);
                    if (dsData != null)
                    {
                        HttpContext.Current.Session["PrintHeaderData"] = dsData.Tables[0].Copy();
                        return JsonConvert.SerializeObject(dsData);
                    }
                }
            }
            catch (Exception ex)
            {
                Log.WriteException(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "SystemError", ex);
            }
            return string.Empty;
        }
        [WebMethod]
        [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
        public static string GetPaymentType(string docEntry)
        {
            try
            {
                string companyDB = string.Empty;

                if (HttpContext.Current.Session["CompanyDB"] != null)
                {
                    companyDB = HttpContext.Current.Session["CompanyDB"].ToString();
                }
                if (companyDB.Length > 0)
                {
                    if (HttpContext.Current.Session["PaymentList"] == null)
                    {
                        DataSet dsData = null;
                        if (docEntry.Length > 0 && int.Parse(docEntry) > 0)
                        {
                            ARInvoiceBLL obj = new ARInvoiceBLL();
                            dsData = obj.GetAllPayment(companyDB, docEntry);
                        }
                        else
                        {
                            CommonBLL obj = new CommonBLL();
                            dsData = obj.GetPaymentType(companyDB);
                        }
                        if (dsData != null)
                        {
                            HttpContext.Current.Session["PaymentList"] = dsData.Tables[0];
                            return JsonConvert.SerializeObject(dsData.Tables[0]);
                        }
                    }
                    else
                    {
                        DataTable tbPayment = (DataTable)HttpContext.Current.Session["PaymentList"];
                        return JsonConvert.SerializeObject(tbPayment);
                    }
                }
            }
            catch (Exception ex)
            {
                Log.WriteException(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "SystemError", ex);
            }
            return string.Empty;
        }
        [WebMethod]
        [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
        public static void UpdatePaymentAmount(string paymentCode, double amount)
        {
            try
            {
                if (HttpContext.Current.Session["PaymentList"] != null)
                {
                    DataTable tbPayment = (DataTable)HttpContext.Current.Session["PaymentList"];
                    if (tbPayment != null)
                    {
                        DataRow[] existsPayment = tbPayment.Select("PaymentCode='" + paymentCode + "'");
                        if (existsPayment.Length > 0)
                        {
                            existsPayment[0]["Amount"] = amount;
                        }

                    }
                    HttpContext.Current.Session["PaymentList"] = tbPayment;
                }
            }
            catch (Exception ex)
            {
                Log.WriteException(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "SystemError", ex);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="docLine"></param>
        private static void CalcRow(Model.INV1 docLine)
        {
            double priceAfterDiscount = 0;
            double totalAfterDiscount = 0;
            double vatSum = 0;
            double totalBeforeDiscount = 0;
            double vatPrcnt = 0, discount = 0, unitPrice = 0, quantity = 0, total = 0;


            vatPrcnt = docLine.VatPrcnt;
            discount = docLine.DiscPrcnt;
            unitPrice = docLine.PriceBefDi;
            quantity = docLine.Quantity;

            priceAfterDiscount = unitPrice * (100 - discount) / 100;
            totalBeforeDiscount = unitPrice * quantity;
            totalAfterDiscount = priceAfterDiscount * quantity;

            vatSum = (totalAfterDiscount * vatPrcnt) / 100;
            total = totalAfterDiscount + vatSum;

            docLine.Price = priceAfterDiscount;
            docLine.VatSum = vatSum;
            docLine.LineTotal = totalAfterDiscount;
            docLine.TotalBefDisc = totalBeforeDiscount;
            docLine.Total = total;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="itemCode"></param>
        /// <param name="cardCode"></param>
        /// <param name="refDate"></param>
        /// <returns></returns>
        private static DataTable GetItemForBarcode(string itemCode, string cardCode, DateTime refDate)
        {
            try
            {
                string companyDB = string.Empty;

                if (HttpContext.Current.Session["CompanyDB"] != null)
                {
                    companyDB = HttpContext.Current.Session["CompanyDB"].ToString();
                }
                if (companyDB.Length > 0)
                {
                    ItemMasterDataBLL obj = new ItemMasterDataBLL();
                    CommonBLL objCommon = new CommonBLL();
                    DataSet dsData = obj.GetOITMByItemCode(companyDB, itemCode);
                    if (HttpContext.Current.Session["DocList"] != null && dsData != null && dsData.Tables.Count > 0)
                    {
                        DataSet dsTax = objCommon.GetTax(companyDB, "O");
                        DataSet dsWarehouse = objCommon.GetWareshouse(companyDB);
                        Model.INV1 docLine = new Model.INV1();
                        List<Model.INV1> lstDocLine = (List<Model.INV1>)HttpContext.Current.Session["DocList"];
                        Model.INV1 existLine = lstDocLine.FirstOrDefault(u => u.ItemCode.ToUpper() == itemCode.ToUpper() && u.LineStatus != "3");

                        if (existLine != null)
                        {
                            existLine.Quantity = existLine.Quantity + 1;

                            if (existLine.U_WebPOSPrice.ToString().ToUpper() == "Y")
                            {
                                double vatIncludeAmt = 1 + (existLine.VatPrcnt / 100);
                                existLine.PriceBefDi = existLine.PriceBefDi / vatIncludeAmt;
                            }

                            // Cal Row
                            CalcRow(existLine);
                        }
                        else
                        {
                            foreach (DataRow r in dsData.Tables[0].Rows)
                            {
                                docLine.Dscription = r["ItemName"].ToString();
                                docLine.ItemCode = r["ItemCode"].ToString();
                                docLine.PriceBefDi = double.Parse(GetSAPItemPrice(cardCode, itemCode, 1, refDate));
                                docLine.Quantity = 1;
                                docLine.unitMsr = r["InvntryUom"].ToString();
                                docLine.VatGroup = r["VatGourpSa"].ToString();
                                docLine.WhsCode = r["DfltWH"].ToString();
                                docLine.SlpCode = "-1";
                                docLine.U_WebPOSPrice = r["U_WebPOSPrice"].ToString();

                                if (dsTax != null && dsTax.Tables.Count > 0)
                                {
                                    DataRow[] rowTax = dsTax.Tables[0].Select("Code = '" + docLine.VatGroup + "'");

                                    if (rowTax.Length > 0)
                                    {
                                        docLine.VatGroupName = rowTax[0]["Name"].ToString();
                                        docLine.VatPrcnt = double.Parse(rowTax[0]["Rate"].ToString());
                                    }
                                }
                                if (dsWarehouse != null && dsWarehouse.Tables.Count > 0 && dsWarehouse.Tables[0].Rows.Count > 0)
                                {
                                    DataRow[] rowWarehouse = dsWarehouse.Tables[0].Select("WhsCode = '" + docLine.WhsCode + "'");

                                    if (rowWarehouse.Length > 0)
                                    {
                                        docLine.WhsName = rowWarehouse[0]["WhsName"].ToString();
                                    }
                                }

                                // Price Include Tax
                                if (r["U_WebPOSPrice"].ToString().ToUpper() == "Y")
                                {
                                    double vatIncludeAmt = 1 + (docLine.VatPrcnt / 100);
                                    docLine.PriceBefDi = docLine.PriceBefDi / vatIncludeAmt;
                                }

                                // Cal Row
                                CalcRow(docLine);
                            }

                            var result = (from m in lstDocLine
                                          select m).OrderByDescending(a => a.LineNum).FirstOrDefault();
                            if (result != null)
                            {
                                docLine.LineNum = (int.Parse(result.LineNum) + 1).ToString();
                            }
                            else
                            {
                                docLine.LineNum = "0";
                            }
                            docLine.DocEntry = "0";
                            lstDocLine.Add(docLine);
                        }
                        HttpContext.Current.Session["DocList"] = lstDocLine;
                        HttpContext.Current.Session["DocCount"] = lstDocLine.Count;
                        return dsData.Tables[0];
                    }
                    else
                    {
                        Log.WriteError(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, Utils.Utils.GetCurrentMethod(), "SAPError", "NO DATA");
                    }
                }
            }
            catch (Exception ex)
            {
                Log.WriteException(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "SystemError", ex);
            }
            return null;
        }
        [WebMethod]
        public static void UserUpdateLine(string lineNum, string itemCode, double quantity, double priceBefDi, double discount,
            string warehouse, string taxCode, double taxRate, string salesPerson, string dscription)
        {
            try
            {
                string companyDB = string.Empty;

                if (HttpContext.Current.Session["CompanyDB"] != null)
                {
                    companyDB = HttpContext.Current.Session["CompanyDB"].ToString();
                }
                if (companyDB.Length > 0)
                {
                    if (HttpContext.Current.Session["DocList"] != null)
                    {
                        Model.INV1 docLine = new Model.INV1();
                        List<Model.INV1> lstDocLine = (List<Model.INV1>)HttpContext.Current.Session["DocList"];
                        Model.INV1 existLine = lstDocLine.FirstOrDefault(u => u.ItemCode.ToUpper() == itemCode.ToUpper() && u.LineStatus != "3" && u.LineNum == lineNum);

                        if (existLine != null)
                        {
                            existLine.Quantity = quantity;
                            existLine.PriceBefDi = priceBefDi;
                            existLine.DiscPrcnt = discount;

                            existLine.SlpCode = salesPerson;
                            existLine.Dscription = dscription;
                            existLine.VatGroup = taxCode;
                            existLine.VatPrcnt = taxRate;
                            existLine.WhsCode = warehouse;
                            if (existLine.U_WebPOSPrice.ToUpper() == "Y")
                            {
                                double vatIncludeAmt = 1 + (existLine.VatPrcnt / 100);
                                existLine.PriceBefDi = existLine.PriceBefDi / vatIncludeAmt;
                            }
                            // Cal Row
                            CalcRow(existLine);
                        }
                        HttpContext.Current.Session["DocList"] = lstDocLine;
                        HttpContext.Current.Session["DocCount"] = lstDocLine.Count;
                    }
                }
            }
            catch (Exception ex)
            {
                Log.WriteException(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "SystemError", ex);
            }
        }
        [WebMethod]
        public static string GetDataByBarcode(string barcode, string cardCode, DateTime refDate)
        {
            try
            {
                string companyDB = string.Empty;

                if (HttpContext.Current.Session["CompanyDB"] != null)
                {
                    companyDB = HttpContext.Current.Session["CompanyDB"].ToString();
                }
                if (companyDB.Length > 0)
                {
                    CommonBLL obj = new CommonBLL();

                    DataSet dsData = obj.GetObjByBarcode(companyDB, barcode);
                    if (dsData != null && dsData.Tables.Count > 0)
                    {
                        DataTable tbResult = dsData.Tables[0];
                        if (tbResult.Rows.Count > 0)
                        {
                            if (tbResult.Rows[0]["ObjType"].ToString() == "2")
                            {
                                if (dsData.Tables[0].Rows.Count > 1)
                                {
                                    HttpContext.Current.Session["POSBPList"] = dsData.Tables[0];
                                    return "2";
                                }
                                else
                                {
                                    return JsonConvert.SerializeObject(dsData.Tables[0]);
                                }
                            }
                            else if (tbResult.Rows[0]["ObjType"].ToString() == "4")
                            {
                                if (tbResult.Rows.Count == 1)
                                {
                                    DataTable tbItem = GetItemForBarcode(tbResult.Rows[0]["ObjCode"].ToString(), cardCode, refDate);
                                    return JsonConvert.SerializeObject(tbItem);
                                }
                                else
                                {
                                    HttpContext.Current.Session["POSItemMasterDataList"] = dsData.Tables[0];
                                    return "4";
                                }
                            }
                        }
                        else
                        {
                            Log.WriteError(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, Utils.Utils.GetCurrentMethod(), "SAPError", "NO DATA");
                            return "-1";
                        }
                    }
                    else
                    {
                        Log.WriteError(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, Utils.Utils.GetCurrentMethod(), "SAPError", "NO DATA");
                        return "-1";
                    }
                }
            }
            catch (Exception ex)
            {
                Log.WriteException(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "SystemError", ex);
            }
            return string.Empty;
        }
        [WebMethod]
        public static string GetDataBySelectedItemCode(string itemCode, string cardCode, DateTime refDate)
        {
            try
            {
                string companyDB = string.Empty;

                if (HttpContext.Current.Session["CompanyDB"] != null)
                {
                    companyDB = HttpContext.Current.Session["CompanyDB"].ToString();
                }
                if (companyDB.Length > 0)
                {
                    CommonBLL obj = new CommonBLL();
                    DataTable tbItem = GetItemForBarcode(itemCode, cardCode, refDate);
                    return JsonConvert.SerializeObject(tbItem);
                }
            }
            catch (Exception ex)
            {
                Log.WriteException(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "SystemError", ex);
            }
            return string.Empty;
        }
        [WebMethod]
        public static string PrintReceipt(string docEntry)
        {
            try
            {
                string sapUser = string.Empty;
                string sapPassword = string.Empty;
                string companyDB = string.Empty;
                string companyName = string.Empty;

                if (HttpContext.Current.Session["LoginUserName"] != null)
                {
                    sapUser = HttpContext.Current.Session["LoginUserName"].ToString();
                }
                if (HttpContext.Current.Session["LoginPassword"] != null)
                {
                    sapPassword = HttpContext.Current.Session["LoginPassword"].ToString();
                }
                if (HttpContext.Current.Session["CompanyDB"] != null)
                {
                    companyDB = HttpContext.Current.Session["CompanyDB"].ToString();
                }
                if (HttpContext.Current.Session["CompanyName"] != null)
                {
                    companyName = HttpContext.Current.Session["CompanyName"].ToString();
                }
                if (companyDB.Length > 0)
                {
                    ARInvoiceBLL obj = new ARInvoiceBLL();
                    DataSet dsData = new DataSet();
                    string html = string.Empty;

                    DataTable tbHeader = null;
                    DataTable tbLine = null;
                    if (HttpContext.Current.Session["PrintHeaderData"] != null)
                    {
                        tbHeader = ((DataTable)HttpContext.Current.Session["PrintHeaderData"]).Copy();
                    }
                    else
                    {
                        DataSet dsHeader = obj.GetDocumentByDocEntry(companyDB, docEntry);
                        if (dsHeader != null && dsHeader.Tables.Count > 0)
                        {
                            tbHeader = dsHeader.Tables[0].Copy();
                            HttpContext.Current.Session["PrintHeaderData"] = tbHeader;
                        }
                    }
                    if (HttpContext.Current.Session["PrintLineData"] != null)
                    {
                        tbLine = ((DataTable)HttpContext.Current.Session["PrintLineData"]).Copy();
                    }
                    if (tbHeader != null && tbLine != null)
                    {
                        tbHeader.TableName = Utils.TableNameDefined.AR_INVOICE_HEADER;
                        tbLine.TableName = Utils.TableNameDefined.AR_INVOICE_LINE;

                        dsData.Tables.Add(tbHeader);
                        dsData.Tables.Add(tbLine);

                        html = obj.CreateReceiptHTML(dsData, companyDB, sapUser, companyName, HttpContext.Current.Server.MapPath("html/receipt.html"));

                        return html;
                    }
                    else
                    {
                        return "Error: Can not print.";
                    }
                }
            }
            catch (Exception ex)
            {
                Log.WriteException(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "SystemError", ex);
                return "Error: " + ex.Message;
            }
            return string.Empty;
        }
        private PrintQueue FindPrinter(string printerName)
        {
            var printers = new PrintServer().GetPrintQueues();
            foreach (var printer in printers)
            {
                if (printer.FullName == printerName)
                {
                    return printer;
                }
            }
            return LocalPrintServer.GetDefaultPrintQueue();
        }
    }
}